<?php
/*md5签名*/
namespace App\Lib;

class signature
{
    /**
     * 签名
     * */
    public static function MakeSign($param, $sign_type = 'MD5')
    {
        $config = config('pay');
        ksort($param);
        
        $string = self::ToUrlParams($param);
        
        $string = $string . "&key=".$config['selfpay']['key'];
        
        if($sign_type == "MD5"){
            $string = md5($string);
        } else if($sign_type == "HMAC-SHA256") {
            $string = hash_hmac("sha256",$string ,$config['selfpay']['key']);
        }
        
        $result = strtoupper($string);
        return $result;
    }
    
    /**
     * 支付验签
     * */
    public static function checkSign($param)
    {
        $sign = $param['sign'];
        if(self::MakeSign($param) != $sign){
            return false;
        }
        return true;
    }
    
    /**
     * 格式化参数格式化成url参数
     */
    public static function ToUrlParams($param)
    {
        $buff = "";
        foreach ($param as $k => $v)
        {
            if($k != "sign" && $v != "" && !is_array($v)){
                $buff .= $k . "=" . $v . "&";
            }
        }
        
        $buff = trim($buff, "&");
        return $buff;
    }
    
}